<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:c="livcos.org/ns/cosmos"
	xmlns:u="livcos.org/ns/cosmos/update"
  xmlns:job="livcos.org/ns/process/job"
  xmlns="livcos.org/ns/doc"
  exclude-result-prefixes="c">

  <xsl:import href="../../style/base.xsl" />
  
  <xsl:param name="objId"/>
  <xsl:param name="scope" select="'content'"/>
	<xsl:param name="id"/>
	<xsl:param name="ref"/>
	<xsl:param name="view"/>

  <xsl:template match="/*">
  	<xsl:apply-templates select="c:request/parameter/*" />
  	<job:feed ref="{$view}" stream="response" base="job"/>
  </xsl:template>
	
	<xsl:template match="*">
	</xsl:template>
	
	<xsl:template match="snapshot">
		<xsl:variable name="entity" select="doc(concat($objId, '.', $scope))//*[@id = $id]"/>
		<xsl:if test="matches($entity/@ref, 'https?://')">
			<xsl:variable name="targetRef">
				<xsl:value-of select="$ref"/>
				<xsl:if test="not($ref)">
					<xsl:value-of select="../group[path = '@ref']/content"/>
				</xsl:if>
			</xsl:variable>
			<xsl:variable name="targetObjId" select="resolve-uri($targetRef, $objId)"/>
			<job:snapshot ref="{$targetObjId}" url="{$entity/@ref}"/>
			<u:context ref="{$objId}" scope="{$scope}">
				<u:context select="*//*[@id = '{$id}']">
					<u:update select="@ref">
						<xsl:value-of select="$targetRef"/>
					</u:update>
					<u:insert select=".">
						<u:attribute name="source">
							<xsl:value-of select="$entity/@ref"/>
						</u:attribute>
					</u:insert>
				</u:context>
			</u:context>
		</xsl:if>
	</xsl:template>
	
</xsl:stylesheet>
